package com.zhengx.wifip2phelperDemo

import android.Manifest
import android.net.NetworkInfo
import android.net.wifi.WifiManager
import android.net.wifi.p2p.WifiP2pDevice
import android.net.wifi.p2p.WifiP2pGroup
import android.net.wifi.p2p.WifiP2pInfo
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import com.zhengx.wifip2phelper.DiscoverListener
import com.zhengx.wifip2phelper.WifiP2PHelper
import com.zhengx.wifip2phelper.WifiStatusChangeListener

import kotlinx.android.synthetic.main.activity_main.*
import pub.devrel.easypermissions.EasyPermissions

class MainActivity : AppCompatActivity(),
        WifiStatusChangeListener,
        DiscoverListener,
    View.OnClickListener{

    /**
    * wifi 连接封装
    * */
    var wifiP2PHelper : WifiP2PHelper?= null

//    var httpFileTransformClient: HttpFileTransformClient ?= null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        wifiP2PHelper = WifiP2PHelper(this, this, this)

        setListenner()
    }

    fun setListenner() {
        enable.setOnClickListener(this)
        disable.setOnClickListener(this)
        discovery.setOnClickListener(this)
        stopDiscovery.setOnClickListener(this)
        connectFirst.setOnClickListener(this)
        disconnect.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when(v?.id) {
            //开启wifi
            R.id.enable -> {
                if (EasyPermissions.hasPermissions(this, Manifest.permission.CHANGE_WIFI_STATE)) {
                    // Already have permission, do the thing
                    wifiP2PHelper?.toggleWifi(true)
                } else {
                    // Do not have permissions, request them now
                    EasyPermissions.requestPermissions(this, "read permission",
                            1, Manifest.permission.CHANGE_WIFI_STATE)
                }
            }
            //关闭wifi
            R.id.disable -> {
                if (EasyPermissions.hasPermissions(this, Manifest.permission.CHANGE_WIFI_STATE)) {
                    // Already have permission, do the thing
                    wifiP2PHelper?.toggleWifi(false)
                } else {
                    // Do not have permissions, request them now
                    EasyPermissions.requestPermissions(this, "read permission",
                            1, Manifest.permission.CHANGE_WIFI_STATE)
                }
            }
            //扫描wifi设备
            R.id.discovery -> {
                wifiP2PHelper?.discoverDevice()
            }
            //关闭扫描
            R.id.stopDiscovery -> {
                wifiP2PHelper?.stopDiscovery()
            }

            //连接第一个扫描到的设备
            R.id.connectFirst -> {
                if (wifiP2PHelper?.deviceList?.size ?: 0  > 0) {
                    wifiP2PHelper?.connectDevice(wifiP2PHelper?.deviceList!!.get(0))
                }
            }

            //断开连接
            R.id.disconnect -> {
                wifiP2PHelper?.discoverDevice()
            }
        }
    }

    override fun onWifiStateChange(previous: Int, nowState: Int) {

        val previousStr : String = getWifiStateStr(previous)
        val nowStr : String = getWifiStateStr(nowState)
        status.text = "${previousStr}->${nowStr}"
    }

    internal fun getWifiStateStr(reason: Int): String{
        return when(reason) {
            WifiManager.WIFI_STATE_ENABLED -> {
                "已开启"
            }

            WifiManager.WIFI_STATE_DISABLED -> {
                "已关闭"
            }

            WifiManager.WIFI_STATE_ENABLING -> {
                "开启中"

            }

            WifiManager.WIFI_STATE_DISABLING -> {
                "关闭中"
            }

            else -> {
                "未知"
            }
        }
    }

    /*======================================WiFi 回调 ===========================================*/
    override fun onWifiP2PEnable() {
    }

    override fun onWifiP2PDisable() {
    }

    override fun onRequestPeers() {
        wifiP2PHelper?.requestPeers()
    }

    override fun onUpdatePeers(devices: List<WifiP2pDevice>) {
    }

    override fun onThisChange(device: WifiP2pDevice) {
        currentInfo.text = device.toString()
    }

    override fun onConnectStateChange(wifiP2pGroup: WifiP2pGroup, wifiP2pInfo: WifiP2pInfo,
                                      networkInfo: NetworkInfo) {

        tvNetworkInfo.text = "GroupInfo:${wifiP2pGroup.toString()}\n P2PInfo:${wifiP2pInfo.toString()}\nNetworkInfo:${networkInfo.toString()}"
        if (networkInfo.isConnected) {
            if (wifiP2pInfo.isGroupOwner) {

            } else {

            }
        }
    }

    override fun onConnectResult(success: Boolean) {
    }


    override fun onDiscoverChange(isConnected: Boolean) {
        if (isConnected) {
            tvDiscoveryStatus.text = "扫描中"
        } else {
            tvDiscoveryStatus.text = "停止"
        }
    }

    override fun onDiscoverStart(startResult: Boolean, reason: Int) {
        if (startResult) {
        } else {

        }
    }

    override fun onStopDiscovery(stopResult: Boolean, reason: Int) {
        if (stopResult)
        else
            ;
    }


    override fun onStart() {
        super.onStart()
        wifiP2PHelper?.registerWifiBroadcast()
    }

    override fun onStop() {
        super.onStop()
        wifiP2PHelper?.unRegisterWifiBroadcast()
    }
}
